<template>
  <div class="article-detail-page" v-loading="loading">
    <div v-if="article" class="article-container">
      <!-- 文章头部 -->
      <div class="article-header">
        <h1 class="article-title">{{ article.title }}</h1>

        <!-- 作者信息 -->
        <div class="author-section">
          <div class="author-info">
            <el-avatar
              :src="getMediaUrl(article.userAvatar)"
              :size="48"
            >
              {{ article.userNickname?.charAt(0) }}
            </el-avatar>
            <div class="author-details">
              <div class="author-name">{{ article.userNickname }}</div>
              <div class="publish-info">
                <span>{{ formatTime(article.publishTime || article.createdTime) }}</span>
                <span class="separator">·</span>
                <span>reading {{ formatCount(article.viewCount) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons" v-if="userStore.isLoggedIn">
            <el-button
              v-if="article.userId === userStore.userInfo?.id"
              type="primary"
              @click="editArticle"
            >
              <el-icon><Edit /></el-icon>
              Edit
            </el-button>
          </div>
        </div>

        <!-- 话题标签 -->
        <div class="article-topics" v-if="article.topics && article.topics.length > 0">
          <el-tag
            v-for="topic in article.topics"
            :key="topic.id"
            class="topic-tag"
          >
            {{ topic.name }}
          </el-tag>
        </div>
      </div>

      <!-- 文章内容 -->
      <div class="article-content">
        <!-- 封面图片 -->
        <div class="article-cover" v-if="article.coverImage">
          <img :src="getMediaUrl(article.coverImage)" :alt="article.title" />
        </div>

        <!-- 文章正文 -->
        <div class="article-body" v-html="article.content"></div>
      </div>

      <!-- 文章底部操作 -->
      <div class="article-footer">
        <div class="article-stats">
          <div class="stats-info">
            <span class="stat-item">
              <el-icon><View /></el-icon>
              {{ formatCount(article.viewCount) }} reading
            </span>
            <span class="stat-item">
              <el-icon><ChatDotRound /></el-icon>
              {{ formatCount(article.commentCount) }} comment
            </span>
          </div>

          <div class="action-buttons">
            <button
              class="action-btn like-btn"
              :class="{ active: article.isLiked }"
              @click="handleLikeArticle"
            >
              <el-icon><CaretTop /></el-icon>
              <span>{{ formatCount(article.likeCount) }}</span>
            </button>

            <button
              class="action-btn collect-btn"
              :class="{ active: article.isCollected }"
              @click="handleCollectArticle"
            >
              <el-icon><Star /></el-icon>
              <span>{{ formatCount(article.collectCount) }}</span>
            </button>

            <button class="action-btn share-btn" @click="handleShare">
              <el-icon><Share /></el-icon>
              <span>share</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <CommentList
          :target-id="article.id"
          :target-type="3"
        />
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="!loading" class="error-state">
      <el-result
        icon="warning"
        title="article not found"
        sub-title="The article may have been deleted or does not exist"
      >
        <template #extra>
          <el-button type="primary" @click="$router.push('/article')">
            back to article list
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {CaretTop, ChatDotRound, Edit, Share, Star, View} from '@element-plus/icons-vue'
import {useUserStore} from '@/stores/user'
import {getArticleDetail, toggleCollectArticle, toggleLikeArticle} from '@/api/article'
import {formatCount, formatTime} from '@/utils/format'
import {getMediaUrl} from '@/utils/media'
import CommentList from '@/components/CommentList.vue'
import {shareContent} from '@/utils/clipboard'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const article = ref(null)

// 生命周期
onMounted(() => {
  loadArticleDetail()
})

// 方法
const loadArticleDetail = async () => {
  loading.value = true
  try {
    const articleId = route.params.id
    const response = await getArticleDetail(articleId)

    if (response.code === 200) {
      article.value = response.data
    } else {
      ElMessage.error(response.message || '获取文章详情失败')
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  } finally {
    loading.value = false
  }
}

const editArticle = () => {
  router.push(`/write?id=${article.value.id}`)
}

const handleLikeArticle = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const response = await toggleLikeArticle(article.value.id)
    if (response.code === 200) {
      article.value.isLiked = !article.value.isLiked
      article.value.likeCount += article.value.isLiked ? 1 : -1
      ElMessage.success(article.value.isLiked ? '点赞成功' : '已取消点赞')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleCollectArticle = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const response = await toggleCollectArticle(article.value.id)
    if (response.code === 200) {
      article.value.isCollected = !article.value.isCollected
      article.value.collectCount += article.value.isCollected ? 1 : -1
      ElMessage.success(article.value.isCollected ? '收藏成功' : '已取消收藏')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleShare = async () => {
  try {
    const result = await shareContent({
      title: article.value.title,
      text: article.value.summary || article.value.title,
      url: window.location.href
    })

    if (result.success && result.method === 'clipboard') {
      ElMessage.success('链接已复制到剪贴板')
    } else if (!result.success && result.reason !== 'cancelled') {
      ElMessage({
        message: `请手动复制链接：${window.location.href}`,
        type: 'info',
        duration: 10000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}
</script>

<style lang="scss" scoped>
.article-detail-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.article-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.article-header {
  padding: 32px 32px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.article-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.3;
  margin: 0 0 24px 0;
}

.author-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 500;
  color: #1a1a1a;
  font-size: 16px;
}

.publish-info {
  font-size: 14px;
  color: #8590a6;

  .separator {
    margin: 0 8px;
  }
}

.article-topics {
  .topic-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

.article-content {
  padding: 32px;
}

.article-cover {
  margin-bottom: 24px;
  text-align: center;

  img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.article-body {
  font-size: 16px;
  line-height: 1.8;
  color: #1a1a1a;

  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin: 24px 0 16px 0;
    font-weight: 600;
    color: #1a1a1a;
  }

  :deep(h1) { font-size: 28px; }
  :deep(h2) { font-size: 24px; }
  :deep(h3) { font-size: 20px; }
  :deep(h4) { font-size: 18px; }

  :deep(p) {
    margin: 16px 0;
    line-height: 1.8;
  }

  :deep(img) {
    max-width: 100%;
    height: auto;
    margin: 16px 0;
    border-radius: 4px;
  }

  :deep(blockquote) {
    margin: 16px 0;
    padding: 16px 20px;
    background: #f7f8fa;
    border-left: 4px solid #1890ff;
    border-radius: 4px;

    p {
      margin: 0;
      color: #666;
      font-style: italic;
    }
  }

  :deep(code) {
    background: #f7f8fa;
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Monaco', 'Consolas', monospace;
    font-size: 14px;
    color: #e74c3c;
  }

  :deep(pre) {
    background: #f7f8fa;
    padding: 16px;
    border-radius: 6px;
    overflow-x: auto;
    margin: 16px 0;

    code {
      background: none;
      padding: 0;
      color: #333;
    }
  }

  :deep(ul), :deep(ol) {
    margin: 16px 0;
    padding-left: 24px;

    li {
      margin: 8px 0;
      line-height: 1.6;
    }
  }
}

.article-footer {
  padding: 24px 32px;
  border-top: 1px solid #f0f0f0;
}

.article-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-info {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #8590a6;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: 1px solid #e1e8ed;
  background: white;
  color: #8590a6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;

  &:hover {
    background: #f7f8fa;
    border-color: #d9d9d9;
  }

  &.active {
    color: #1890ff;
    border-color: #1890ff;
    background: #f0f8ff;
  }
}

.comments-section {
  margin-top: 32px;
  padding: 24px 32px;
  background: white;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.error-state {
  text-align: center;
  padding: 60px 20px;
}
</style>
